// @import Pages Collection from pages.js

// 配置默认的layout
Router.configure({
	layoutTemplate:'defaultLayout',
	notFoundTemplate: 'notFound',
	loadingTemplate: 'loading'
});

// static web
Router.route('staticWeb',{
	path: '/:page?',
	waitOn: function(){
		var waiton = [];
		waiton.push(Meteor.subscribe(Pages._name));
		return waiton;
	},
	action: function(){
		// this.layout("hello");
		var page = this.params.page || 'home';
		var pageModel = Pages.findOne({page: page});
		var isFound = !!pageModel;
		var pageTitle = isFound ? pageModel.title : "not found";

		document.title = "Site Name | " + pageTitle;
		//当前选中的页面的模型
		Session.set('staticWebContent', pageModel); 
		//当前选中的页面的page标记
		Session.set('page', page); 

		var tmpl = isFound ? "pages" : "notFound";
		this.render(tmpl);
	}
});

Router.route('userPage',{
	path: '/user/:action?',
	onBeforeAction:function(){
		if(Meteor.user() == null){
			this.next();
		} else {
			var action = this.params.action;
			if(action == 'signout'){
				Meteor.logout(function(error){
					if(!error){
						this.redirect("/");
					}
				});
			} else {
				console.log("/user user logined in, so redirect to home page");
				this.redirect("/");
			}
		}
	},
	action: function(){
		var action = this.params.action;
		console.log(action);
		if(action == 'signup' || action == 'signin') {
			this.render(action);
		} else if(action == 'signout'){
			this.redirect("/");
		} else {
			this.redirect("/");
		}
	}
});

// Router.route('/api/user/signin', {where: 'server'})
// .post(function(){
// 	var email = this.request.body.email;
// 	var password = this.request.body.password;
// 	console.log("email:" + email);
// 	console.log("password:" + password);
// 	Meteor.loginWithPassword(email, password, function (error) {
// 		if(error){
// 			FlashMessages.sendError(error.reason);
// 			this.response.end("{code: 0}")
// 		} else {
// 			FlashMessages.sendError("登录成功");
// 			this.response.end("{code: 1}");
// 		}
// 	});
	
// });

if(Meteor.isServer){
	Rap.addLogin("/api/user/signin");
	Rap.addRegister("/api/user/signup");
}

